package pers.cz.resource;

import pers.cz.io.IOUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.net.URL;

/**
 * @program: JefConfig
 * @description: 抽象资源类加载器，初步实现加载功能，具体的扩展功能由实现类去实现
 * @author: Cheng Zhi
 * @create: 2022-07-11 21:50
 **/
public abstract class AbstractJefResourceLoader implements JefResourceLoader {

    @Override
    public URL getResource(String name) {
        return null;
    }

    @Override
    public InputStream getResourceAsStream(String fileName) {

        URL url = getResource(fileName);

        try {
            return url == null? null : url.openStream();
        } catch (Exception e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public BufferedReader getResourceAsReader(String fileName, String charset) {

        URL url = getResource(fileName);
        try {

            return IOUtils.getReader(url.openStream(), charset);
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }

    public URL toUrl(String fileName) {

        if (fileName == null || fileName.length() == 0) {
            return null;
        }

        try {
            File file = new File(fileName);
            URL url = file.toURI().toURL();
            return url;
        } catch (Exception e) {

        }

        return null;
    }

    public URL toUrl(File file) {

        try {
            return file.toURI().toURL();
        } catch (Exception e) {

        }

        return null;
    }
}
